package com.palpiteiro.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.palpiteiro.bean.Usuario;

public class UsuarioConnectionFactory {

	private static Connection conn = null;
	
	public static Connection getConn() {
		if(conn == null)
			try {
				Class.forName("org.postgresql.Driver");
	            conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/BD_Usuario","postgres", "admin");  
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}   
		return conn;
	}
	
	public static void setConn(Connection conn) {
		UsuarioConnectionFactory.conn = conn;
	}
	
	public static ResultSet selectUsuario(String email, String senha) throws SQLException{

		String sql = "";
		PreparedStatement stmt = null;
		ResultSet rs = null;
		conn = UsuarioConnectionFactory.getConn();
		sql = "select id_usuario,nome,cpf,email,senha,valorInicial,valorAtual,estrategia"
				+ " from \"Usuario\".usuario" + " where email = ? and senha = ?;";
		stmt = conn.prepareStatement(sql);
		stmt.setString(1, email);
		stmt.setString(2, senha);
		rs = stmt.executeQuery();
		
		return rs;
	}
	
	public static void insertUsuario(Usuario usuario) throws SQLException{
		String sql = "";
		PreparedStatement stmt = null;
		conn = UsuarioConnectionFactory.getConn();
		sql = "insert into \"Usuario\".usuario (nome,email,senha,valorInicial,valorAtual" + " values(?,?,?,?,?)";
		stmt = conn.prepareStatement(sql);
		stmt.setString(1, usuario.getNome());
		stmt.setString(2, usuario.getEmail());
		stmt.setString(3, usuario.getSenha());
		stmt.setDouble(4, usuario.getValorInicial());
		stmt.setDouble(5, usuario.getValorAtual());
		
		stmt.executeUpdate();
	}
	
	public static void updateUsuario(Usuario usuario) throws SQLException{

		String sql = "";
		PreparedStatement stmt = null;
		conn = UsuarioConnectionFactory.getConn();
		sql = "update \"Usuario\".usuario set nome=?,email=?,senha=?,valorInicial=?,valorAtual=?" + " where id_usuario = ?;";
		stmt = conn.prepareStatement(sql);
		stmt.setString(1, usuario.getNome());
		stmt.setString(2, usuario.getEmail());
		stmt.setString(3, usuario.getSenha());
		stmt.setDouble(4, usuario.getValorInicial());
		stmt.setDouble(5, usuario.getValorAtual());
		stmt.setInt(6, usuario.getId_usuario());
		
		stmt.executeUpdate();
	}
}
